package application;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.colorchooser.ColorSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import universe.Block;
import display.MiniBlockDisplay;

public class Configuration extends JDialog implements WindowListener{

	private static final long serialVersionUID = 1L;

	private Tetris theTetris;

	private JColorChooser colorChooser;
	private JComboBox selectTheme;

	public Configuration(Tetris pTetris){
		super();


		/*for(int i = 0; i < application.Utils.getThemes().size(); i++)
			selectTheme.addItem(application.Utils.getThemes().get(i).getName());

		selectTheme.setSelectedIndex(application.Utils.themeChoosen);
*/


		theTetris = pTetris;

		int labelSize = 200;

		this.setTitle("Configuration");
		this.setSize(new Dimension(600,535));
		this.setLayout(new BorderLayout());


		this.setLocationRelativeTo(null);
		this.setResizable(false);
		this.setModal(true);
		this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);


		this.addWindowListener(this);

		JTabbedPane tabbedPane = new JTabbedPane();

		JPanel configGame = new JPanel();
		configGame.setLayout(new GridLayout(6, 1));
		JPanel configSon = new JPanel();
		configSon.setLayout(new GridLayout(6, 2));

		JPanel configKey = new JPanel();
		Container configColor = new Container();
		JPanel configTheme = new JPanel();

		//CHOIX DU THEME
		selectTheme = new JComboBox();
		selectTheme.addActionListener(new ThemeListener());
		loadComboThemes();
		configTheme.add(selectTheme);


		//SON ACTIVE OU NON
		JCheckBox oBoxSound = new JCheckBox("Son activé");
		if(application.Utils.soundActivated) oBoxSound.setSelected(true);
		oBoxSound.addActionListener(new SoundListener());
		configSon.add(oBoxSound);

		//CHOIX DE LA MUSIQUE
		String[] songList = sound.Utils.getSongList();
		JComboBox selectSong = new JComboBox(songList);
		selectSong.setSelectedItem(sound.Utils.gameBackgroundTone);
		selectSong.addActionListener(new SoundSelectorListener());
		configSon.add(selectSong);

		//MODE FACILE
		JCheckBox oBoxClone = new JCheckBox("Afficher le fantôme de la pièce en cours");
		if(display.Utils.DISPLAY_CLONE) oBoxClone.setSelected(true);
		oBoxClone.addActionListener(new CloneListener());
		configGame.add(oBoxClone);		

		//MODE GRAVITY
		JCheckBox oBoxGravity = new JCheckBox("Utiliser la gravité");
		if(Utils.gravityActivated) oBoxGravity.setSelected(true);
		oBoxGravity.addActionListener(new GravityListener());
		configGame.add(oBoxGravity);

		//DEPLACER A GAUCHE
		JPanel panelKeyLeft = new JPanel();
		panelKeyLeft.setLayout(new FlowLayout());
		JLabel labelKeyLeft = new JLabel("Déplacer la pièce à gauche");
		labelKeyLeft.setPreferredSize(new Dimension(labelSize, 20));
		JTextField fieldKeyLeft = new JTextField(KeyEvent.getKeyText(Utils.keyMoveLeft));
		fieldKeyLeft.setPreferredSize(new Dimension(100, 20));

		JTextField fieldKeyLeft2 = new JTextField(KeyEvent.getKeyText(Utils.keyMoveLeft2));
		fieldKeyLeft2.setPreferredSize(new Dimension(100, 20));

		fieldKeyLeft.setEditable(false);
		fieldKeyLeft2.setEditable(false);
		fieldKeyLeft.addKeyListener(new TetrisKeyListener(fieldKeyLeft,1));
		fieldKeyLeft2.addKeyListener(new TetrisKeyListener(fieldKeyLeft2,7));
		panelKeyLeft.add(labelKeyLeft);
		panelKeyLeft.add(fieldKeyLeft);
		panelKeyLeft.add(fieldKeyLeft2);
		configKey.add(panelKeyLeft);

		//DEPLACER A DROITE
		JPanel panelKeyRight = new JPanel();
		panelKeyRight.setLayout(new FlowLayout());
		JLabel labelKeyRight = new JLabel("Déplacer la pièce à droite");
		labelKeyRight.setPreferredSize(new Dimension(labelSize, 20));
		JTextField fieldKeyRight = new JTextField(KeyEvent.getKeyText(Utils.keyMoveRight));
		fieldKeyRight.setPreferredSize(new Dimension(100, 20));
		JTextField fieldKeyRight2 = new JTextField(KeyEvent.getKeyText(Utils.keyMoveRight2));
		fieldKeyRight2.setPreferredSize(new Dimension(100, 20));
		fieldKeyRight.setEditable(false);
		fieldKeyRight2.setEditable(false);
		fieldKeyRight.addKeyListener(new TetrisKeyListener(fieldKeyRight,2));
		fieldKeyRight2.addKeyListener(new TetrisKeyListener(fieldKeyRight2,8));
		panelKeyRight.add(labelKeyRight);
		panelKeyRight.add(fieldKeyRight);
		panelKeyRight.add(fieldKeyRight2);
		configKey.add(panelKeyRight);

		//DEPLACER EN BAS
		JPanel panelKeyDown = new JPanel();
		panelKeyDown.setLayout(new FlowLayout());
		JLabel labelKeyDown = new JLabel("Déplacer la pièce en bas");
		labelKeyDown.setPreferredSize(new Dimension(labelSize, 20));
		JTextField fieldKeyDown = new JTextField(KeyEvent.getKeyText(Utils.keyMoveDown));
		fieldKeyDown.setPreferredSize(new Dimension(100, 20));
		JTextField fieldKeyDown2 = new JTextField(KeyEvent.getKeyText(Utils.keyMoveDown2));
		fieldKeyDown2.setPreferredSize(new Dimension(100, 20));
		fieldKeyDown.setEditable(false);
		fieldKeyDown2.setEditable(false);
		fieldKeyDown.addKeyListener(new TetrisKeyListener(fieldKeyDown,3));
		fieldKeyDown2.addKeyListener(new TetrisKeyListener(fieldKeyDown2,9));
		panelKeyDown.add(labelKeyDown);
		panelKeyDown.add(fieldKeyDown);
		panelKeyDown.add(fieldKeyDown2);
		configKey.add(panelKeyDown);

		//ROTATIONNER
		JPanel panelKeyRotate = new JPanel();
		panelKeyRotate.setLayout(new FlowLayout());
		JLabel labelKeyRotate = new JLabel("Tourner la pièce");
		labelKeyRotate.setPreferredSize(new Dimension(labelSize, 20));
		JTextField fieldKeyRotate = new JTextField(KeyEvent.getKeyText(Utils.keyRotate));
		fieldKeyRotate.setPreferredSize(new Dimension(100, 20));
		JTextField fieldKeyRotate2 = new JTextField(KeyEvent.getKeyText(Utils.keyRotate2));
		fieldKeyRotate2.setPreferredSize(new Dimension(100, 20));
		fieldKeyRotate.setEditable(false);
		fieldKeyRotate2.setEditable(false);
		fieldKeyRotate.addKeyListener(new TetrisKeyListener(fieldKeyRotate,4));
		fieldKeyRotate2.addKeyListener(new TetrisKeyListener(fieldKeyRotate2,10));
		panelKeyRotate.add(labelKeyRotate);
		panelKeyRotate.add(fieldKeyRotate);
		panelKeyRotate.add(fieldKeyRotate2);
		configKey.add(panelKeyRotate);

		//DROP DOWNER
		JPanel panelKeyDropDown = new JPanel();
		panelKeyDropDown.setLayout(new FlowLayout());
		JLabel labelKeyDropDown = new JLabel("Laisser tomber la pièce");
		labelKeyDropDown.setPreferredSize(new Dimension(labelSize, 20));
		JTextField fieldKeyDropDown = new JTextField(KeyEvent.getKeyText(Utils.keyDropDown));
		fieldKeyDropDown.setPreferredSize(new Dimension(100, 20));
		JTextField fieldKeyDropDown2 = new JTextField(KeyEvent.getKeyText(Utils.keyDropDown2));
		fieldKeyDropDown2.setPreferredSize(new Dimension(100, 20));
		fieldKeyDropDown.setEditable(false);
		fieldKeyDropDown2.setEditable(false);
		fieldKeyDropDown.addKeyListener(new TetrisKeyListener(fieldKeyDropDown,5));
		fieldKeyDropDown2.addKeyListener(new TetrisKeyListener(fieldKeyDropDown2,11));
		panelKeyDropDown.add(labelKeyDropDown);
		panelKeyDropDown.add(fieldKeyDropDown);
		panelKeyDropDown.add(fieldKeyDropDown2);
		configKey.add(panelKeyDropDown);

		//PAUSER
		JPanel panelKeyPause = new JPanel();
		panelKeyPause.setLayout(new FlowLayout());
		JLabel labelKeyPause = new JLabel("Mettre en pause");
		labelKeyPause.setPreferredSize(new Dimension(labelSize, 20));
		JTextField fieldKeyPause = new JTextField(KeyEvent.getKeyText(Utils.keyPause));
		fieldKeyPause.setPreferredSize(new Dimension(100, 20));
		JTextField fieldKeyPause2 = new JTextField(KeyEvent.getKeyText(Utils.keyPause2));
		fieldKeyPause2.setPreferredSize(new Dimension(100, 20));
		fieldKeyPause.setEditable(false);
		fieldKeyPause2.setEditable(false);
		fieldKeyPause.addKeyListener(new TetrisKeyListener(fieldKeyPause,6));
		fieldKeyPause2.addKeyListener(new TetrisKeyListener(fieldKeyPause2,12));
		panelKeyPause.add(labelKeyPause);
		panelKeyPause.add(fieldKeyPause);
		panelKeyPause.add(fieldKeyPause2);
		configKey.add(panelKeyPause);

		//COULEURS DES PIECES
		configColor.setSize(1000,1000);
		configColor.setLayout(new BorderLayout());
		JPanel panelColor = new JPanel();
		panelColor.setLayout(new FlowLayout(FlowLayout.CENTER));
		panelColor.setPreferredSize(new Dimension(1000, 1000));
		// Fond transparent
		panelColor.setOpaque(false);


		colorChooser = new JColorChooser();

		colorChooser.setPreviewPanel(new JPanel());

		int offset = 10 + display.Utils.getMiniBlockDisplayHeightPx + display.Utils.bordureBlockSelected * 2;

		Block blockA = new Block(universe.Utils.getBlockA());
		blockA.setCurrentPosition(0);
		MiniBlockDisplay miniBlockA = new MiniBlockDisplay(configColor, blockA, "A");
		miniBlockA.setSelected(true);
		colorChooser.getSelectionModel().setSelectedColor(miniBlockA.getColor());

		Block blockB = new Block(universe.Utils.getBlockB());
		blockB.setCurrentPosition(0);
		MiniBlockDisplay miniBlockB = new MiniBlockDisplay(configColor, blockB, "B");
		miniBlockB.setOffsetY(offset);

		Block blockC = new Block(universe.Utils.getBlockC());
		blockC.setCurrentPosition(0);
		MiniBlockDisplay miniBlockC = new MiniBlockDisplay(configColor, blockC, "C");
		miniBlockC.setOffsetY(offset*2);

		Block blockD = new Block(universe.Utils.getBlockD());
		blockD.setCurrentPosition(0);
		MiniBlockDisplay miniBlockD = new MiniBlockDisplay(configColor, blockD, "D");
		miniBlockD.setOffsetY(offset*3);

		Block blockE = new Block(universe.Utils.getBlockE());
		blockE.setCurrentPosition(0);
		MiniBlockDisplay miniBlockE = new MiniBlockDisplay(configColor, blockE, "E");
		miniBlockE.setOffsetY(offset*4);

		Block blockF = new Block(universe.Utils.getBlockF());
		blockF.setCurrentPosition(0);
		MiniBlockDisplay miniBlockF = new MiniBlockDisplay(configColor, blockF, "F");
		miniBlockF.setOffsetY(offset*5);

		Block blockG = new Block(universe.Utils.getBlockG());
		blockG.setCurrentPosition(0);
		MiniBlockDisplay miniBlockG = new MiniBlockDisplay(configColor, blockG, "G");
		miniBlockG.setOffsetY(offset*6);

		miniBlockA.addMouseListener(new blockListener());
		miniBlockB.addMouseListener(new blockListener());
		miniBlockC.addMouseListener(new blockListener());
		miniBlockD.addMouseListener(new blockListener());
		miniBlockE.addMouseListener(new blockListener());
		miniBlockF.addMouseListener(new blockListener());
		miniBlockG.addMouseListener(new blockListener());

		colorChooser.getSelectionModel().addChangeListener(new ColorChooserListener(configColor));

		configColor.add(panelColor,BorderLayout.CENTER);
		panelColor.add(colorChooser);

		JLabel labelColor = new JLabel("Choisissez un bloc en cliquant dessus puis choisissez votre couleur.");
		panelColor.add(labelColor);


		UIManager.put("TabbedPane.contentAreaColor", new Color(238, 238, 238));
		SwingUtilities.updateComponentTreeUI(tabbedPane);

		tabbedPane.addTab("Jeu",null,configGame,"Configuration du jeu");
		tabbedPane.addTab("Son",null,configSon,"Modifier le son");
		tabbedPane.addTab("Contrôles",null, configKey, "Modifier les touches");
		tabbedPane.addTab("Couleurs",null, configColor, "Modifier les couleurs");
		tabbedPane.addTab("Thèmes",null,configTheme,"Modifier le thème");

		this.add(tabbedPane,BorderLayout.CENTER);

		//BOUTON OK
		JPanel south = new JPanel();
		JButton oButtonOk = new JButton(application.Utils.buttonOk);
		oButtonOk.addActionListener(theTetris.getActionListener()); //new ButtonListener());
		south.add(oButtonOk,BorderLayout.SOUTH);
		this.add(south,BorderLayout.SOUTH);

	}



	private void loadComboThemes(){
		//CHOIX DU THEME
		int choosenIndex = application.Utils.themeChoosen;

		selectTheme.removeAllItems();

		for(int i = 0; i < application.Utils.getThemes().size(); i++)
			selectTheme.addItem(application.Utils.getThemes().get(i).getName());

		selectTheme.setSelectedIndex(choosenIndex);
	}


	private void onClosed(){

		theTetris.getTheTetrisData().saveColors();
		theTetris.getTheTetrisData().loadColors();
		loadComboThemes();

		//GESTION SON
		if(theTetris.getGame() == null){
			//ON EST SUR LE MENU D'ACCUEIL
			//System.out.println("on met a jour la checkbox");

			for(int i = 0; i < theTetris.getHomeMenu().getComponents().length; i++){
				if(theTetris.getHomeMenu().getComponent(i) instanceof JCheckBox){
					JCheckBox chkbox = (JCheckBox) theTetris.getHomeMenu().getComponent(i);
					if(theTetris.getGame() == null){
						if(application.Utils.soundActivated){
							chkbox.setSelected(true);
							//System.out.println("la musique doit se lancer");
							theTetris.getHomeMenuSound().resume();
						}
						else{
							chkbox.setSelected(false);
							//System.out.println("la musique doit pas se lancer");
							theTetris.getHomeMenuSound().pause();
						}
					}
				}
			}
		}
		//ON EST SUR UNE PARTIE
		else{
			//System.out.println("une partie est en cours");
			if(application.Utils.soundActivated){
				//	System.out.println("une partie est en cours et le son est activé donc on joue");
				if(!theTetris.getGame().isGamePaused())
					theTetris.getGame().getBackgroundSound().resume();
			}
			else{
				//	System.out.println("une partie est en cours mais le son est desactivé donc on ne joue pas");
			}
		}
		//System.out.println("fin de onClosed()");
	}

	/*class ButtonListener implements ActionListener{
			@Override
			public void actionPerformed(ActionEvent e) {
				Configuration.this.dispose();

			}
		}*/

	static class SoundListener implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent e) {
			if(((JCheckBox)e.getSource()).isSelected()){
				application.Utils.soundActivated = true;
			}
			else{
				application.Utils.soundActivated = false;
			}
		}
	}

	class CloneListener implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent e) {
			if(((JCheckBox)e.getSource()).isSelected()){
				display.Utils.DISPLAY_CLONE = true;

			}else{
				display.Utils.DISPLAY_CLONE = false;
			}
		}
	}

	class GravityListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			if(((JCheckBox)e.getSource()).isSelected()){
				Utils.gravityActivated = true;

			}else{
				Utils.gravityActivated = false;
			}
		}
	}

	class SoundSelectorListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {

			JComboBox jcb = (JComboBox) e.getSource();
			String wav = (String) jcb.getSelectedItem();
			//System.out.println(wav);
			sound.Utils.gameBackgroundTone = wav;
			if(theTetris.getGame() instanceof universe.Game){
				//theTetris.getGame().setBackgroundSound(new Player(wav, true));
				theTetris.getGame().reloadBackgroundSound();
				//theTetris.getGame().getBackgroundSound().setPaused(true);
			}
		}

	}


	class TetrisKeyListener implements KeyListener{
		private JTextField theField;
		private int action;

		public TetrisKeyListener(JTextField pField, int pNumber){
			theField = pField;
			action = pNumber;
		}


		@Override
		public void keyPressed(KeyEvent e) {
			switch(action){
			case 1: Utils.keyMoveLeft = e.getKeyCode(); break;
			case 2: Utils.keyMoveRight = e.getKeyCode(); break;
			case 3: Utils.keyMoveDown = e.getKeyCode(); break;
			case 4: Utils.keyRotate = e.getKeyCode(); break;
			case 5: Utils.keyDropDown = e.getKeyCode(); break;
			case 6: Utils.keyPause = e.getKeyCode(); break;
			case 7: Utils.keyMoveLeft2 = e.getKeyCode(); break;
			case 8: Utils.keyMoveRight2 = e.getKeyCode(); break;
			case 9: Utils.keyMoveDown2 = e.getKeyCode(); break;
			case 10: Utils.keyRotate2 = e.getKeyCode(); break;
			case 11: Utils.keyDropDown2 = e.getKeyCode(); break;
			case 12: Utils.keyPause2 = e.getKeyCode(); break;
			default : System.err.println("C'est la merde!!");
			}
			this.theField.setText(KeyEvent.getKeyText(e.getKeyCode()));
		}

		@Override
		public void keyReleased(KeyEvent e) {
			// TODO Auto-generated method stub
		}

		@Override
		public void keyTyped(KeyEvent e) {
			// TODO Auto-generated method stub
		}
	}

	public class blockListener implements MouseListener{
		@Override
		public void mouseClicked(MouseEvent e) {
			JColorChooser theColorChooser = null;

			MiniBlockDisplay miniBlock = (MiniBlockDisplay) e.getSource();
			Container theContainer = miniBlock.getContainer();

			for(int i = 0; i < theContainer.getComponents().length; i++){
				if(theContainer.getComponent(i) instanceof MiniBlockDisplay){
					((MiniBlockDisplay) theContainer.getComponent(i)).setSelected(false);
				}
				else if(theContainer.getComponent(i) instanceof JPanel){
					JPanel thePanel = (JPanel) theContainer.getComponent(i);

					for(int j = 0; j < thePanel.getComponents().length; j++){
						if(thePanel.getComponent(j) instanceof JColorChooser){
							theColorChooser = (JColorChooser) thePanel.getComponent(j);
						}
					}
				}
			}
			miniBlock.setSelected(true);
			theColorChooser.getSelectionModel().setSelectedColor(miniBlock.getColor());
			miniBlock.getContainer().repaint();
		}

		@Override
		public void mouseEntered(MouseEvent e) {
			// TODO Auto-generated method stub	
		}

		@Override
		public void mouseExited(MouseEvent e) {
			// TODO Auto-generated method stub	
		}

		@Override
		public void mousePressed(MouseEvent e) {
			// TODO Auto-generated method stub	
		}

		@Override
		public void mouseReleased(MouseEvent e) {
			// TODO Auto-generated method stub	
		}	
	}

	public class ColorChooserListener implements ChangeListener {
		Container theContainer;

		public ColorChooserListener(Container pCon){
			theContainer = pCon;
		}
		@Override
		public void stateChanged(ChangeEvent e) {
			MiniBlockDisplay theBlock;
			for(int i = 0; i < theContainer.getComponents().length; i++){
				if(theContainer.getComponent(i) instanceof MiniBlockDisplay){


					theBlock = (MiniBlockDisplay) theContainer.getComponent(i);

					if(theBlock.isSelected()){
						Color c = ((ColorSelectionModel) e.getSource()).getSelectedColor();

						theBlock.setColor(c);
						theBlock.getContainer().repaint();
					}
				}
			}
		}

	}

	class ThemeListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			int index = ((JComboBox) e.getSource()).getSelectedIndex();

			if(application.Utils.getThemes().size() >= index){
				application.Utils.setCurrentTheme(index);
			}
		}
	}


	@Override
	public void windowClosed(WindowEvent e) {
		System.out.println("windowClosed");
		this.removeWindowListener(this);
		onClosed();
	}

	@Override
	public void windowActivated(WindowEvent e) {}
	@Override
	public void windowClosing(WindowEvent e) {}
	@Override
	public void windowDeactivated(WindowEvent e) {}
	@Override
	public void windowDeiconified(WindowEvent e) {}
	@Override
	public void windowIconified(WindowEvent e) {}
	@Override
	public void windowOpened(WindowEvent e) {}

}
